﻿using UnityEngine;
//#if UNITY_STANDALONE_OSX
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using System.Collections.Generic;
using System.IO;
//#endif

public class XCodeProjectMod 
{
//#if UNITY_STANDALONE_OSX
    
    public static string CurrentBuildChannelName = "";

    [PostProcessBuild]
    private static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath)
    {
        if (buildTarget != BuildTarget.iOS)
            return;
        PBXProject pbxProject = null;
        XCodeProjectConfig setting = null;
        string pbxProjPath = PBXProject.GetPBXProjectPath(buildPath);
        string targetGuid = null;

        #region 设置 .pbxproj
        Debug.Log("XCode 工程导出结束 . 开始设置 [ .pbxproj ] 配置");
        var jsonPath = string.Format("{0}/{1}/{2}.json", XCodeProjectConfig.ChannelConfigFodler, CurrentBuildChannelName, CurrentBuildChannelName);
        var assetText = AssetDatabase.LoadAssetAtPath<TextAsset>(jsonPath);
        Debug.Log(jsonPath);
        setting = JsonUtility.FromJson<XCodeProjectConfig>(assetText.text);

        pbxProject = new PBXProject();
        pbxProject.ReadFromString(File.ReadAllText(pbxProjPath));
        targetGuid = pbxProject.TargetGuidByName(PBXProject.GetUnityTargetName());

        //TODO SetBuildProperties
        Debug.Log(string.Format("配置Target属性共:{0} 个", setting.SetBuildProperty.Count));
        foreach (var item in setting.SetBuildProperty)
        {
            var arr = item.Split(';');
            var key = arr[0].Trim(); var thisValue = arr[1].Trim();
            Debug.Log(string.Format("<color=white>SetBuildProperty : KEY : [{0}] , Value : [{1}]</color>",key,thisValue));
            pbxProject.SetBuildProperty(targetGuid, key, thisValue);
        }

        //TODO SystemCapabilites
        // foreach (var item in setting.SetSystemCapabilites)
        //{
        //   pbxProject.setS
        // }

        Debug.Log("引用内部框架");
        //引用内部框架
        foreach (string framework in setting.FrameworkList)
        {
            var arr = framework.Split(':');
            var frameworkName = arr[0];

            if (frameworkName.EndsWith(".tbd") || frameworkName.EndsWith(".dylib")) //添加tdb动态库
            {
                string fileGuidSqlite = pbxProject.AddFile("usr/lib/" + frameworkName, "Libraries/" + frameworkName, PBXSourceTree.Sdk);
                pbxProject.AddFileToBuild(targetGuid, fileGuidSqlite);
            }
            else if (frameworkName.EndsWith(".framework")) //添加系统静态库
            {
                pbxProject.AddFrameworkToProject(targetGuid, frameworkName, arr.Length >= 2);
            }
        }

        //TODO AddFileToBuild
         //-----------

        Debug.Log("设置OTHER_LDFLAGS");
        //设置OTHER_LDFLAGS
        pbxProject.UpdateBuildProperty(targetGuid, XCodeProjectConfig.LINKER_FLAG_KEY, setting.LinkerFlagArray, null);

        Debug.Log("添加 Keychain ");
        var filePath = string.Format("{0}/{1}/KeychainAccessGroups.plist", Application.dataPath ,setting.keychainPath ); ;
        var projecPath = "KeychainAccessGroups.plist";
        pbxProject.AddFile(filePath, projecPath);


        Debug.Log(string.Format("拷贝添加文件夹到项目：From：{0} ， To: {1}", setting.CopyDirectoryPath, buildPath));
        if (!string.IsNullOrEmpty(setting.CopyDirectoryPath))
            DirectoryProcessor.CopyAndAddBuildToXcode(pbxProject, targetGuid, setting.CopyDirectoryPath, buildPath, "IOSPorter",false);

        Debug.Log("设置宏：");
        //编译器标记（Compiler flags）
        foreach (XCodeProjectConfig.CompilerFlagsSet compilerFlagsSet in setting.CompilerFlagsSetList)
        {
            foreach (string targetPath in compilerFlagsSet.TargetPathList)
            {
                if (!pbxProject.ContainsFileByProjectPath(targetPath))
                    continue;
                string fileGuid = pbxProject.FindFileGuidByProjectPath(targetPath);
                List<string> flagsList = pbxProject.GetCompileFlagsForFile(targetGuid, fileGuid);
                flagsList.Add(compilerFlagsSet.Flags);
                pbxProject.SetCompileFlagsForFile(targetGuid, fileGuid, flagsList);
                //Debug.Log(string.Format("   添加宏：{0}",));
            }
        }

        //Debug.Log("设置Framework Search Paths");
        ////设置Framework Search Paths
        //pbxProject.UpdateBuildProperty(targetGuid, XCodeProjectConfig.FRAMEWORK_SEARCH_PATHS_KEY, setting.FrameworkSearchPathArray, null);

        File.WriteAllText(pbxProjPath, pbxProject.WriteToString());
        Debug.Log("[ .pbxproj ] 配置结束 !");
        #endregion

        #region CopyFile

        Debug.Log("替换文件到项目：");
        
        //已经存在的文件，拷贝替换
        foreach (XCodeProjectConfig.CopeFiles file in setting.CopeFilesList)
        {
            Debug.Log(string.Format("Frome:{0} : To:{1}",file.sourcePath,file.copyPath));
            var source = XCEditorUtils.CombinePaths(Application.dataPath, file.sourcePath);
            var target = XCEditorUtils.CombinePaths(buildPath, file.copyPath);

            DirectoryProcessor.CopyFiles(source, target);
        }

        //File.Copy(Application.dataPath + "/Editor/XCodeAPI/UnityAppController.h", buildPath + "/Classes/UnityAppController.h", true);
        //File.Copy(Application.dataPath + "/Editor/XCodeAPI/UnityAppController.mm", buildPath + "/Classes/UnityAppController.mm", true);
        #endregion

        #region 设置Plist
        Debug.Log("设置Plist");
        InfoPlistProcessor.SetInfoPlist(buildPath, setting);
        #endregion

        Debug.Log("配置设置结束！ 开始调用打包！");
        //TODO
    }

    private static string GetBoolElementValue(bool value)
    {
        return value ? "YES" : "NO";
    }
    //#endif
}